package mobileann.mafamily.utils;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONObject;

import com.mobileann.mafamily.R;
import com.mofind.android.base.L;
import com.mofind.android.net.HttpUtils;
import com.mofind.android.net.JSONParser;
import com.mofind.android.net.HttpUtils.HttpResultCallback;
import com.mofind.widget.dialog.DialogUtil;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.AlertDialog;
import android.app.KeyguardManager;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.DialogInterface.OnCancelListener;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.graphics.Rect;
import android.net.Uri;
import android.os.Handler;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.CompoundButton.OnCheckedChangeListener;
import mobileann.mafamily.act.main.FS;
import mobileann.mafamily.act.member.CaptureActivity;
import mobileann.mafamily.db.model.ActionModel;
import mobileann.mafamily.db.model.UserModel;
import mobileann.mafamily.entity.ActionEntity3;
import mobileann.mafamily.entity.MemberInfoEntity;
import mobileann.mafamily.entity.UserInfoEntity;
import mobileann.mafamily.model.UDPSocket;
import mobileann.mafamily.service.UpdateService;
import static android.app.ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND;
import static android.app.ActivityManager.RunningAppProcessInfo.IMPORTANCE_VISIBLE;

/**
 * 重构showApplyDialog方法，CaptureActivity使用
 * @change ADRIAN
 */
public class MySelfUtils {
	private static MySelfUtils _instance;
	private static final String TAG = "MySelfUtils";
	public static final int REFRESHFID_SUCCESS=561;
	public static final int REFRESHFID_ERROR=562;

	public synchronized static MySelfUtils getInstance() {
		if (_instance == null) {
			_instance = new MySelfUtils();
		}
		return _instance;

	}

	/*
	 * 判断邀请者是否是光棍
	 */
	public boolean inviter() {
		boolean isBachor = false;
		UserModel model = new UserModel(FS.getInstance());
		List<UserInfoEntity> users = new ArrayList<UserInfoEntity>();
		users = model.queryUserInfoAll();
		if (users.size() == 1) {
			isBachor = true;
		}
		return isBachor;
	}

	/**
	 * 统计模块的点击次数
	 * 
	 * @param c
	 * @param clickTag
	 *            模块标识
	 */
	public void getTagClick(Context c, int clickTag) {
		ActionEntity3 actionEntity3 = new ActionEntity3(String.valueOf(clickTag), 1);
		ActionModel actionModel = new ActionModel(c);
		List<ActionEntity3> actionEntity3s = new ArrayList<ActionEntity3>();
		actionEntity3s = actionModel.getCount(clickTag);
		int count = actionEntity3s.size();
		if (actionEntity3s.size() > 0) {
			actionEntity3 = actionEntity3s.get(actionEntity3s.size() - 1);
			count = actionEntity3.getCount();
			actionEntity3.setActionNum(clickTag);
			actionEntity3.setCount(++count);
			actionModel.insertClickTimes(actionEntity3);
		}
		actionModel.insertClickTimes(actionEntity3);
	}


	/**
	 * 判断被邀请者是否是同一个家庭的成员
	 * 
	 * @param invitedUid
	 * @return
	 */
	public boolean isAFamily(String invitedUid) {
		boolean isAFamily = false;
		if (!FS.getInstance().mMemberAll.isEmpty()) {
			for (int i = 0; i < FS.getInstance().mMemberAll.size(); i++) {
				if (FS.getInstance().mMemberAll.get(i).getUid()
						.equals(invitedUid)) {
					isAFamily = true;
					break;
				}
			}
		}
		return isAFamily;
	}

	/**
	 * 发送邀请/申请请求
	 * 
	 * @param c
	 * @param addUid
	 *            被邀请者的uid
	 * @param role
	 *            被邀请者要被添加的角色
	 * @param flag
	 *            根据标志位显示要弹出的提示
	 */
	public void sendRequest(Activity c, String addUid, String role, int flag) {
		if (NetUtils.getInstance().netstate() == 0) {
			showToast(c, "当前没有网络连接,请检查后重试");
		} else {
			UDPSocket.getInstance(c).sendNewInviteMemberRequest(
					FS.getInstance().self().getFid(),
					FS.getInstance().self().getUid(), addUid, role);
			if (flag == 1) {
				showToast(c, "已添加，等待对方管理员同意。");
			}
			if (flag == 4) {
				showToast(c, "已添加，等待对方同意。");
			}
			if (flag == 5) {
				showToast(c, "邀请已发送。");
			}
			if (flag != 4) {
				c.finish();
			}
		}
	}

	/**
	 * 申请加入家庭
	 * 
	 * @param act
	 * @param uid
	 *            被邀请者的uid
	 * @param flag
	 *            根据标志位显示要弹出的提示
	 * 给《确定》《取消》按钮添加点击事件跳出扫描界面
	 * @change ADRIAN
	 */
	public void showApplyDialog(final Activity act, final String uid,
			final int flag) {
		AlertDialog.Builder builder = new AlertDialog.Builder(act);
		builder.setTitle("提示");
		builder.setMessage("对方已有家庭。是否申请加入对方家庭？");
		builder.setPositiveButton("是", new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				sendRequest(act, uid, "1", flag);
			}
		});
		builder.setNegativeButton("否", null);
		builder.show();
	}

	/**
	 * 重写方法，增加传递Handler功能
	 * @param act
	 * @param uid
	 * @param flag
	 * @param context
	 * @author ADRIAN
	 */
	public void showApplyDialog(final Activity act, final String uid,
			final int flag, final Handler handler){
		AlertDialog.Builder builder = new AlertDialog.Builder(act);
		builder.setTitle("提示");
		builder.setMessage("对方已有家庭。是否申请加入对方家庭？");
		builder.setPositiveButton("是", new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				sendRequest(act, uid, "1", flag);
				handler.sendEmptyMessage(CaptureActivity.BACHLER_ADD_UNBACHLER);
			}
		});
		builder.setNegativeButton("否", new OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				handler.sendEmptyMessage(CaptureActivity.BACHLER_ADD_UNBACHLER);
			}
		});
		builder.show();
	}

	private void showToast(Context c, String tips) {
		Toast.makeText(c, tips, Toast.LENGTH_SHORT).show();
	}

	public void getAddMemberRole(Context c, String uid) {
		if (NetUtils.getInstance().netstate() == 0) {
			Toast.makeText(c, "当前没有网络连接,请检查后重试", Toast.LENGTH_SHORT).show();
		} else {
			UDPSocket.getInstance(c).sendNymReadInfoRequest(uid);
		}
	}

	private List<UserInfoEntity> members;

	public List<UserInfoEntity> getMembers() {
		return members;
	}

	public void setMembers(List<UserInfoEntity> members) {
		this.members = members;
	}

	public void autoLogin(Context c, Handler handler) {
		if (NetUtils.getInstance().netstate() == 0) {
			Toast.makeText(c, "您的网络已断开，请检查重试。", Toast.LENGTH_SHORT).show();
		} else {
			if (TextUtils.isEmpty(SPUtils.getVerifyCode())) {
			} else {
				LoginUtils.getInstance().doLogin(c, SPUtils.getNum(),
						SPUtils.getVerifyCode(),
						System.currentTimeMillis() / 1000 + "", handler);
				LoginUtils.getInstance().setTimeOut(handler);
			}
		}
	}

	/*
	 * 判断应用是否在后台运行
	 */
	public boolean isBackgroundRunning(Context c) {
		String processName = "com.mobileann.mafamily";
		ActivityManager activityManager = (ActivityManager) c
				.getSystemService(Context.ACTIVITY_SERVICE);
		KeyguardManager keyguardManager = (KeyguardManager) c
				.getSystemService(Context.KEYGUARD_SERVICE);
		if (activityManager == null)
			return false;
		List<ActivityManager.RunningAppProcessInfo> processList = activityManager
				.getRunningAppProcesses();
		for (ActivityManager.RunningAppProcessInfo process : processList) {
			if (process.processName.startsWith(processName)) {
				boolean isBackground = process.importance != IMPORTANCE_FOREGROUND
						&& process.importance != IMPORTANCE_VISIBLE;
				boolean isLockedState = keyguardManager
						.inKeyguardRestrictedInputMode();
				if (isBackground || isLockedState)
					return true;
				else
					return false;
			}
		}
		return false;
	}

	/**
	 * 获得当前系统的亮度模式 SCREEN_BRIGHTNESS_MODE_AUTOMATIC=1 为自动调节屏幕亮度
	 * SCREEN_BRIGHTNESS_MODE_MANUAL=0 为手动调节屏幕亮度
	 */
	public int getBrightnessMode() {
		int brightnessMode = Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL;
		try {
			brightnessMode = Settings.System.getInt(FS.getInstance()
					.getContentResolver(),
					Settings.System.SCREEN_BRIGHTNESS_MODE);
		} catch (Exception e) {
			L.e(TAG, "获得当前屏幕的亮度模式失败：", e);
		}
		return brightnessMode;
	}

	/**
	 * 设置当前系统的亮度模式 SCREEN_BRIGHTNESS_MODE_AUTOMATIC=1 为自动调节屏幕亮度
	 * SCREEN_BRIGHTNESS_MODE_MANUAL=0 为手动调节屏幕亮度
	 */
	public void setBrightnessMode(int brightnessMode) {
		try {
			Settings.System.putInt(FS.getInstance().getContentResolver(),
					Settings.System.SCREEN_BRIGHTNESS_MODE, brightnessMode);
		} catch (Exception e) {
//			Log.e(TAG, "设置当前屏幕的亮度模式失败：", e);
		}
	}

	/**
	 * 获得当前系统的亮度值： 0~255
	 */
	public int getSysScreenBrightness() {
		int screenBrightness = MAX_BRIGHTNESS;
		try {
			screenBrightness = Settings.System.getInt(FS.getInstance()
					.getContentResolver(), Settings.System.SCREEN_BRIGHTNESS);
		} catch (Exception e) {
//			Log.e(TAG, "获得当前系统的亮度值失败：", e);
		}
		return screenBrightness;
	}

	/**
	 * 设置当前系统的亮度值:0~255
	 */
	public void setSysScreenBrightness(int brightness) {
		try {
			ContentResolver resolver = FS.getInstance().getContentResolver();
			Uri uri = Settings.System.getUriFor(Settings.System.SCREEN_BRIGHTNESS);
			Settings.System.putInt(resolver, Settings.System.SCREEN_BRIGHTNESS, brightness);
			resolver.notifyChange(uri, null); // 实时通知改变
		} catch (Exception e) {
//			Log.e(TAG, "设置当前系统的亮度值失败：", e);
		}
	}

	/**
	 * 设置屏幕亮度，这会反映到真实屏幕上
	 * 
	 * @param activity
	 * @param brightness
	 */
	public void setActScreenBrightness(Activity activity, int brightness) {
		WindowManager.LayoutParams lp = activity.getWindow().getAttributes();
		lp.screenBrightness = brightness / (float) MAX_BRIGHTNESS;
		activity.getWindow().setAttributes(lp);
	}

	/**
	 * 显示调节亮度的设置对话框
	 * 
	 * @param act
	 */
	public void showBrightnessSettingsDialog(final Activity act) {
		if (act == null) {
			return;
		}
		final int oldBrightness = getSysScreenBrightness(); // 当前系统的亮度
		final int oldBrightnessMode = getBrightnessMode(); // 当前系统的亮度模式
		boolean autoMode = (oldBrightnessMode == Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC); // 是否自动调节亮度模式
		LayoutInflater inflater = act.getLayoutInflater();
		View dialogLayout = inflater.inflate(R.layout.dlg_auto_screenlight,
				null);
		CheckBox cbAutoMode = (CheckBox) dialogLayout
				.findViewById(R.id.cb_auto_mode); // 自动调节亮度
		cbAutoMode.setChecked(autoMode);
		final SeekBar seekbar = (SeekBar) dialogLayout
				.findViewById(R.id.seekbar); // 手动调节亮度
		if (autoMode) {
			seekbar.setEnabled(false);
		} else {
			seekbar.setEnabled(true);
		}
		int progress = oldBrightness - MIN_BRIGHTNESS; // SeekBar的值范围：0~225，代表的亮度值是30~255。
		seekbar.setProgress(progress < 0 ? 0 : progress);
		seekbar.setMax(MAX_BRIGHTNESS - MIN_BRIGHTNESS); // 最大值：225
		// 自动调节亮度选项改变时
		cbAutoMode.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			@Override
			public void onCheckedChanged(CompoundButton buttonView,
					boolean isChecked) {
				if (isChecked) {
					int light = getSysScreenBrightness();
					setBrightnessMode(Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC);
					seekbar.setProgress(light - MIN_BRIGHTNESS);
					seekbar.setEnabled(false);
				} else {
					setBrightnessMode(Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL);
					seekbar.setEnabled(true);
				}
			}
		});
		// 手动调节亮度滑块滑动时
		seekbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
			@Override
			public void onStopTrackingTouch(SeekBar seekBar) {
			}

			@Override
			public void onStartTrackingTouch(SeekBar seekBar) {
			}

			@Override
			public void onProgressChanged(SeekBar seekBar, int progress,
					boolean fromUser) {
				int brightness = progress + MIN_BRIGHTNESS; // 实际亮度
				// 亮度滑块滑动时，实时改变屏幕亮度
				setActScreenBrightness(act, brightness); // 改变当前屏幕亮度
				setSysScreenBrightness(brightness); // 改变系统屏幕亮度
			}
		});
		// 显示调节亮度的dialog
		AlertDialog.Builder builder = new AlertDialog.Builder(act);
		builder.setTitle("屏幕舒适度");
		builder.setView(dialogLayout);
		builder.setPositiveButton(android.R.string.ok,
				new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {
				// 点击确定按钮，恢复activity亮度设置
				setActScreenBrightness(act, -MAX_BRIGHTNESS);
			}
		});
		builder.setNegativeButton(android.R.string.cancel,
				new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {
				// 点击取消按钮，则需要还原亮度模式和亮度值的设置
				recoverBrightnessSetting(act, oldBrightnessMode,
						oldBrightness);
			}
		});
		builder.setOnCancelListener(new OnCancelListener() { // 点击返回键/dialog外部等让dialog消失的事件
			@Override
			public void onCancel(DialogInterface dialog) {
				recoverBrightnessSetting(act, oldBrightnessMode, oldBrightness);
			}
		});
		builder.show();
	}

	/**
	 * 还原亮度模式和亮度值的设置
	 * 
	 * @param act
	 * @param brightnessMode
	 * @param brightness
	 */
	private void recoverBrightnessSetting(final Activity act,
			final int brightnessMode, final int brightness) {
		setBrightnessMode(brightnessMode);
		setSysScreenBrightness(brightness);
		setActScreenBrightness(act, -MAX_BRIGHTNESS);
	}

	/** 可调节的最小亮度值 */
	public static final int MIN_BRIGHTNESS = 30;
	/** 可调节的最大亮度值 */
	public static final int MAX_BRIGHTNESS = 255;

	/*
	 * 判断是否有哪个权限
	 */
	public boolean hasAuthority(Context c, String authority) {
		boolean hasAuthority = false;
		PackageManager pm = c.getPackageManager();
		hasAuthority = (PackageManager.PERMISSION_GRANTED == pm
				.checkPermission(authority, "com.mobileann.mafamily"));
		return hasAuthority;
	}

	private boolean isMapsInstalled(Context c,String pkname) {
	    try {
		ApplicationInfo info = c.getPackageManager().getApplicationInfo(
					pkname, 0);
		return true;
	    } catch (PackageManager.NameNotFoundException e) {
		return false;
	    }
	}
//	private boolean isBaiduMapsInstalled(Context c) {
//		try {
//			c.getPackageManager().getApplicationInfo(
//					"com.baidu.BaiduMap", 0);
//			return true;
//		} catch (PackageManager.NameNotFoundException e) {
//			return false;
//		}
//	}
	/*
	 * 百度地图和调起的web页：详见百度LBS开放平台
	 * http://developer.baidu.com/map/wiki/index.php?title=uri/api/android
	 * http://developer.baidu.com/map/wiki/index.php?title=uri/api/web
	 * 高德地图：详见高德LBS开放平台http://lbs.amap.com/api/uri-api/android-uri-explain/
	 */
	public void goMaps(Context c, double lat, double lon,String nickName,String address) {
		Intent i = new Intent();
		if (isMapsInstalled(c,"com.baidu.BaiduMap")) {//百度地图
			Intent intent1;
			try {
				intent1 = Intent.getIntent("intent://map/marker?location="+lat+","+lon+"&title=\""+nickName+"\"的位置&content="+address+"&src=跟屁虫#Intent;scheme=bdapp;package=com.baidu.BaiduMap;end");
				c.startActivity(intent1);
//			    intent1 = Intent.getIntent("intent://map/marker?location=40.047669,116.313082&title=\""+nickName+"\"的位置&content=百度奎科大厦&src=yourCompanyName|yourAppName#Intent;scheme=bdapp;package=com.baidu.BaiduMap;end");
//			    c.startActivity(intent1); //启动调用 
			} catch (URISyntaxException e) {
				e.printStackTrace();
			}
		} else if (isMapsInstalled(c,"com.autonavi.minimap")) {//高德地图
			try {
				i.setData(Uri
						.parse("androidamap://viewMap?sourceApplication=跟屁虫&poiname=\""+nickName+"\"的位置&lat="+(lat-0.005636)+"&lon="+(lon-0.00677)+"&dev=0"));
				c.startActivity(i);
			} catch (Exception e) {
			}
//		} else if(isMapsInstalled(c, "com.google.android.apps.maps")){
//		    Uri uri = Uri.parse("http://maps.google.com/maps?f=dsaddr=startLat startLng&"
//		    	+ ""
//		    	+ "=endLat endLng&hl=en");
//			    Intent it = new Intent(Intent.ACTION_VIEW,uri);
//			    c.startActivity(it);
		}else{
//			 i.setData(Uri.parse(("http://api.map.baidu.com/marker?location=39.916979519873,116.41004950566&title=我的位置&content=百度奎科大厦&output=html")));
//			i.setData(Uri.parse("http://api.map.baidu.com/marker?location="
//					+ lat + "," + lon +"&title=\""+nickName+"\"的位置&content="+ address+"&output=html"));
		    try {
			c.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://api.map.baidu.com/marker?location="
				+ lat + "," + lon +"&title=\""+nickName+"\"的位置&content="+ address+"&output=html")));
		    } catch (Exception e) {
			Toast.makeText(c, "请安装地图软件进行导航", Toast.LENGTH_SHORT).show();
		    }
		}
		// try {
		// Uri mUri = Uri
		// .parse("geo:31.249351,121.45905");
		// intent = new Intent(Intent.ACTION_VIEW, mUri);
		// startActivity(intent);
		// } catch (Exception e) {
		// Toast.makeText(mActivity, "未安装地图", Toast.LENGTH_SHORT).show();
		// }
	}
	public boolean isViewCovered(View adview,final View view)  
	 {  
	         View currentView = view;  
	             
	         Rect currentViewRect = new Rect();  
	         boolean partVisible =currentView.getGlobalVisibleRect(currentViewRect);  
	         boolean totalHeightVisible = (currentViewRect.bottom - currentViewRect.top) >= adview.getMeasuredHeight();  
	         boolean totalWidthVisible = (currentViewRect.right - currentViewRect.left) >= adview.getMeasuredWidth();  
	         boolean totalViewVisible = partVisible && totalHeightVisible && totalWidthVisible;  
	         if (!totalViewVisible)//if any part of the view is clipped by any of its parents,return true  
	                 return true;  
	             
	         while (currentView.getParent() instanceof ViewGroup)  
	         {  
	                 ViewGroup currentParent = (ViewGroup) currentView.getParent();  
	                 if (currentParent.getVisibility() != View.VISIBLE)//if the parent of view is not visible,return true  
	                         return true;  
	                     
	                 int start = indexOfViewInParent(currentView, currentParent);  
	                 for (int i = start + 1; i < currentParent.getChildCount(); i++)  
	                 {  
	                         Rect viewRect = new Rect();  
	                         view.getGlobalVisibleRect(viewRect);  
	                         View otherView = currentParent.getChildAt(i);  
	                         Rect otherViewRect = new Rect();  
	                         otherView.getGlobalVisibleRect(otherViewRect);  
	                         if (Rect.intersects(viewRect, otherViewRect))//if view intersects its older brother(covered),return true  
	                                 return true;  
	                 }  
	                 currentView = currentParent;  
	         }  
	         return false;  
	 }  
	   
	   
	 private int indexOfViewInParent(View view, ViewGroup parent)  
	 {  
	         int index;  
	         for (index = 0; index < parent.getChildCount(); index++)  
	         {  
	                 if (parent.getChildAt(index) == view)  
	                         break;  
	         }  
	         return index;  
	}
	 public void getNewFid(final String uid,final String urad,final Handler handler){
	     HttpUtils.startHttpGet(URLUtils.URL_TASK_GET+uid+"_"+urad+"_variety", new HttpResultCallback() {
	        
	        @Override
	        public void result(String url, boolean isResult, String jsonStr) {
	    	if(isResult){
	    	    String json = TripleDESUtil.getJsonObjStr(uid,urad, jsonStr);
	    	    FS.getInstance().cleanData(FS.getInstance());
	    	    if(!TextUtils.isEmpty(json)){
	    		JSONObject jo = JSONParser.getJSONObject(json);
			String status=JSONParser.getString(jo, "status");
			if(TextUtils.isEmpty(status)){
			    String role=JSONParser.getString(jo, "role");
			    String fid=JSONParser.getString(jo, "fid");
			    String frad=JSONParser.getString(jo, "frad");
			    MemberInfoEntity entity = new MemberInfoEntity(uid, urad,
				    SPUtils.getMySelf(SPUtils.MYNAME), role, SPUtils.getMySelf(SPUtils.MYPHONE), SPUtils.getMySelf(SPUtils.MYAVATOR));
			    entity.setFrad(frad);
			    entity.setFid(fid);
			    entity.setIrad(SPUtils.getMySelf(SPUtils.MYIRAD));
			    SPUtils.saveMySelf(entity);
			    // 为使用老版本加入
			    UserInfoEntity userInfo = new UserInfoEntity();
			    userInfo.setUid(SPUtils.getMySelf(SPUtils.MYPHONE));
			    userInfo.setFid(fid);
			    userInfo.setNickname(SPUtils.getMySelf(SPUtils.MYNAME));
			    userInfo.setTelephone(SPUtils.getMySelf(SPUtils.MYPHONE));
			    userInfo.setRole(Integer.parseInt(role));
			    if (SPUtils.getMySelf(SPUtils.MYLOCKPWD) != null) {
				userInfo.setScLockPwd(SPUtils.getMySelf(SPUtils.MYLOCKPWD));
			    }
			    SPUtils.saveSelf(userInfo);
			    FS.getInstance().self().setTelephone(SPUtils.getMySelf(SPUtils.MYPHONE));
			    FS.getInstance().self().setUid(SPUtils.getMySelf(SPUtils.MYPHONE));
			    FS.getInstance().self().setRole(Integer.parseInt(role));
			    FS.getInstance().self().setNickname(SPUtils.getMySelf(SPUtils.MYNAME));
			    FS.getInstance().self().setFid(fid);
			    if(handler!=null){
				handler.obtainMessage(REFRESHFID_SUCCESS).sendToTarget();
			    }
			}else{
			    if(handler!=null){
				handler.obtainMessage(REFRESHFID_ERROR).sendToTarget();
			    }
			}
	    	    }else{
	    		if(handler!=null){
				handler.obtainMessage(REFRESHFID_ERROR).sendToTarget();
			}
	    	    }
	    	}
	        }
	    });
	 }

    public void getNetTime() {
	URL url;
	try {
	    url=new URL("http://www.bjtime.cn");//取得资源对象
	       URLConnection uc=url.openConnection();//生成连接对象
	       uc.connect(); //发出连接
	       long ld=uc.getDate(); //取得网站日期时间
	       Date date=new Date(ld); //转换为标准时间对象
	    // 分别取得时间中的小时，分钟和秒，并输出
//	    Log.i("multicast","LLL"+
//		    date + ", " + date.getHours() + "时" + date.getMinutes()
//			    + "分" + date.getSeconds() + "秒");
	} catch (MalformedURLException e) {
	    e.printStackTrace();
	}// 取得资源对象
	catch (IOException e) {
	    e.printStackTrace();
	}
    }
    private Map<String, String> getApkUpdatePara(Context c, String uid) {
		Map<String, String> map = new HashMap<String, String>();
		map.put("uid", uid);
		map.put("imei", PhoneInfoUtils.getIMEI(c));
		map.put("imsi", PhoneInfoUtils.getIMSI(c));
		map.put("uuid", PhoneInfoUtils.getMyUUID(c));
		map.put("key", URLUtils.getKey(c, uid));
		map.put("os_name", "android");
		map.put("cs_version", PhoneInfoUtils.getVersionCode(c));
		map.put("cs_type", "1");
		return map;
	}
	/*
	 * 判断是否需要更新
	 */
	public void getUpdateApp(final Context c,final boolean isSetup) {
		HttpUtils.startHttpPost(URLUtils.URL_APK_UPDATE,
				getApkUpdatePara(c, SPUtils.getMySelf(SPUtils.MYUID)),
				new HttpUtils.HttpResultCallback() {

					@Override
					public void result(String url, boolean isResult,
							String jsonStr) {
						if (isResult) {
							try {
								JSONObject jo = JSONParser
										.getJSONObject(jsonStr);
								
								String status = JSONParser.getString(jo,
										"status");
								String version = JSONParser.getString(jo,
										"version");
								URLUtils.updateVersionName = JSONParser
										.getString(jo, "ext_version");
								String change_log = JSONParser.getString(jo,
										"change_log");
								URLUtils.downloadPath = JSONParser.getString(
										jo, "url");
								String force = JSONParser
										.getString(jo, "force");
								String view=JSONParser.getString(jo, "view");
								JSONArray ja = JSONParser
										.getJSONArray(change_log);
								String log = "";
								if ("true".equals(status) && version == null) {// 当前是最新版本不需要更新
									if(isSetup)
									Toast.makeText(c, "当前为最新版本",
											Toast.LENGTH_SHORT).show();
								} else if ("false".equals(status)) {// 数据出错
									if(isSetup)
									Toast.makeText(c, "数据出错",
											Toast.LENGTH_SHORT).show();
								} else {
									if (ja.length() > 0) {
										for (int i = 0; i < ja.length(); i++) {
											log += JSONParser.getString(ja, i)
													+ "\n";
										} 
									} else {
										log = "无更新日志";
									}
									log = URLUtils.updateVersionName + "\n\n"
											+ log;
									if (version != null
											&& URLUtils.downloadPath != null) {
										TextView tv = new TextView(c);
										tv.setPadding(20, 20, 20, 20);
										tv.setText(log);
										if ("true".equals(force)) {
											DialogUtil
													.showViewDialogAsForce(c,"新版本-强烈建议更新到此版本",
															tv,
															new DialogInterface.OnClickListener() {
																@Override
																public void onClick(
																		DialogInterface dialog,
																		int which) {
																	Intent intent = new Intent(c,
																			UpdateService.class);
																	c.startService(intent);
																}
															});
										} else {
											if(isSetup){//设置界面逻辑不变
											DialogUtil
													.showViewDialog(c,"新版本",
															tv,
															new DialogInterface.OnClickListener() {
																@Override
																public void onClick(
																		DialogInterface dialog,
																		int which) {
																	Intent intent = new Intent(c,
																			UpdateService.class);
																	c.startService(intent);
																}
															}, true);
										}else{//开启跟屁虫的时候，先判断view是否为空
											if(!TextUtils.isEmpty(view)){//弹出
												String[] roles=view.split(",");
												for(int i=0;i<roles.length;i++){
													if((FS.getInstance().self().getRole()+"").equals(roles[i])){
														DialogUtil
														.showViewDialog(c,"新版本",
																tv,
																new DialogInterface.OnClickListener() {
																	@Override
																	public void onClick(
																			DialogInterface dialog,
																			int which) {
																		Intent intent = new Intent(c,
																				UpdateService.class);
																		c.startService(intent);
																	}
																}, true);
														break;
													}
												}
											}
										}
										}
									}
								}
							} catch (Exception e) {
								;
							}
						}
					}
				});
	}
}
